package cn.somkit.fmt.action;

import cn.somkit.fmt.utils.OsInfoUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/upload")
public class UploadAction {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${somkit.upload.path.windows}")
    private String windows_path;

    @Value("${somkit.upload.path.linux}")
    private String linux_path;

    @GetMapping("/index")
    public String index() throws Exception{
        return "upload";
    }

    @PostMapping("/execute")
    @ResponseBody
    public Map<String, Object> execute(HttpServletRequest request) throws Exception{
        //多个文件上传  就只是简单的多文件上传保存在本地的磁盘
        if (request instanceof MultipartHttpServletRequest mrequest) {
            List<MultipartFile> files = mrequest.getFiles("file");
            // 取出每一个上传文件
            for (MultipartFile file : files) {
                try {
                    this.saveFile(file);        // 保存上传信息
                } catch (Exception e) {
                    logger.error("文件保存失败：{}", e.getMessage());
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("valid", true);
        result.put("message", "上传成功");
        return result;
    }

    /**
     * 文件保存处理
     * @param file 上传文件
     * @throws Exception 上传异常
     */
    public void saveFile(MultipartFile file) throws Exception {
        try {
            String path = OsInfoUtil.isWindows() ? windows_path :
                    OsInfoUtil.isLinux() ? linux_path : null;
            assert path != null;
            String filePath = "";
            if (file != null && file.getSize() > 0) {					// 有文件上传
                filePath = path + File.separator + file.getOriginalFilename();
                File saveFile = new File(filePath) ;
                file.transferTo(saveFile);		// 文件保存
                logger.info("文件保存成功：{}", filePath);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
